package edu.hsbremen.android;

import java.util.Date;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.util.Log;

/**
 * @author jpsnake
 *
 */
public class calenderProvider extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		setContentView(R.layout.main);
		
		String calName;
		String calId;
		
		// Get the given intent
		Bundle extras = getIntent().getExtras();

		// Get the local calendar
		String[] projection = new String[] { "_id", "name" };
		Uri calendars = Uri.parse("content://com.android.calendar/calendars");

		Cursor managedCursor = managedQuery(calendars, projection, null, null, null);
		
		if (managedCursor.moveToFirst()) {
			int nameColumn = managedCursor.getColumnIndex("name");
			int idColumn = managedCursor.getColumnIndex("_id");
			do {
				calName = managedCursor.getString(nameColumn);
				calId = managedCursor.getString(idColumn);
			} while (managedCursor.moveToNext());
		}		

		// Create a new event
		ContentValues event = new ContentValues();
	
		// Create the Date object
		Date d = new Date();
		d.setMonth(extras.getInt("month"));
		d.setYear(extras.getInt("year") - 1900);
		d.setDate(extras.getInt("day"));
		d.setHours(extras.getInt("hour"));
		d.setMinutes(extras.getInt("minute"));
		d.setSeconds(00);
		long startTime = d.getTime();
		Log.d("Datum1", d.toString());
		d.setHours(extras.getInt("hour") + 1);
		d.setMinutes(extras.getInt("minute"));
		d.setSeconds(00);
		long endTime = d.getTime();
		Log.d("Datum2", d.toString());
		
		// Set all properties for the calendar event
		// calender_id == 1 because this way the entry will be done in the first calendar
		// otherwise it will choose the last calendar in the phone
		event.put("calendar_id", 1);
		event.put("title", extras.getString("what"));
		event.put("eventLocation", extras.getString("where"));		
		event.put("dtstart", startTime);
		event.put("dtend", endTime);
		
		if (extras.getString("contact") == null){
			event.put("description", extras.getString("what"));
		}else {
			event.put("description", extras.getString("what") + "\n\n\nTeilnehmer: " + extras.getString("contact"));

		}

		// forward the event to the calendar
		Uri eventsUri = Uri.parse("content://com.android.calendar/events");
		Uri url = getContentResolver().insert(eventsUri, event);
		
		this.finish();
	}
}